package com.csit.util;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * 
 * @Description: 文件操作工具类
 * @Copyright: 福州骏华信息有限公司 (c)2012
 * @Created Date : 2012-8-7
 * @author longweier
 * @vesion 1.0
 */
public class FileUtil {
	
	private static Object lock = new Object();
	
	/**
	 * 
	 * @Description: 往文件里面写一个字符串
	 * @param
	 * @Create: 2012-8-7 上午09:04:46
	 * @author longweier
	 * @update logs
	 * @param fileName
	 * @param note
	 * @return
	 * @throws Exception
	 */
	public static void write(String fileName,String note)
	{
		BufferedWriter out = null;
		
		try {
			out = new BufferedWriter(new FileWriter(fileName));
			out.write(note, 0, note.length());
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(out !=null){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 转换图片大小，不变形
	 * 
	 * @param img
	 *            图片文件
	 * @param width
	 *            图片宽
	 * @param height
	 *            图片高
	 */
	public static void changeImge(File sourceImg,File destImg, int width, int height) {
		FileOutputStream fos = null;
		synchronized (lock) {
			try {
				Image image = ImageIO.read(sourceImg);
				//图片尺寸的大小处理，如果长宽都小于规定大小，则返回，如果有一个大于规定大小，则等比例缩放
				int srcH = image.getHeight(null);
				int srcW = image.getWidth(null);
				if (srcH <= height && srcW <= width) {
					BufferedImage bufferedImage = new BufferedImage(width, height,BufferedImage.TYPE_3BYTE_BGR);

					bufferedImage.getGraphics().drawImage(image.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0,0, srcW, srcH, null);

					fos = new FileOutputStream(destImg);

					JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);

					encoder.encode(bufferedImage);
					fos.close();
					return;
				}
				int tmpH = width;
				int tmpW = height;
				//在长度和宽度都做了限制，不能超过设定值
				while (srcH > height || srcW > width) {
					if(srcW > width) {
						tmpH = srcH * width / srcW;
						srcH = tmpH;
						srcW=width;	
					}
					if(srcH > height) {
						tmpW = srcW * height / srcH;
						srcW = tmpW;
						srcH=height;
					}
				}

				BufferedImage bufferedImage = new BufferedImage(srcW, srcH,
						BufferedImage.TYPE_3BYTE_BGR);

				bufferedImage.getGraphics().drawImage(
						image.getScaledInstance(srcW, srcH, Image.SCALE_SMOOTH), 0,
						0, srcW, srcH, null);

				fos = new FileOutputStream(destImg);

				JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);

				encoder.encode(bufferedImage);
				
			} catch (IOException e) {
				e.printStackTrace();
				throw new IllegalStateException("图片转换出错！", e);
			} finally{
				try {
					if(fos !=null){
						fos.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}
	
	/**
	 * 
	 * @Description: 删除一个文件
	 * @param
	 * @Create: 2012-8-7 上午09:05:12
	 * @author longweier
	 * @update logs
	 * @param file
	 * @return
	 * @throws Exception
	 */
	public static void deleteFile(File file){
		
		if(file.exists()){
			
			file.delete();
		}
	}
	
	/**
	 * 
	 * @Description: 保存文件
	 * @param
	 * @Create: 2012-8-7 上午09:07:10
	 * @author longweier
	 * @update logs
	 * @param source
	 * @param dest
	 * @return
	 * @throws Exception
	 */
	public static void saveFile(File source,File dest){
		InputStream is = null;
		OutputStream os = null;
		try {
			 is = new  BufferedInputStream(new FileInputStream(source));
			
			 os = new BufferedOutputStream(new FileOutputStream(dest));
			
			int len = 0;
			
			byte[] buffer = new byte[1024];

			while (-1 != (len = is.read(buffer)))
			{
				os.write(buffer, 0, len);
				
			}
			
			os.flush();
			
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if(os !=null){
					os.close();
				}
				if(is!=null){
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 
	 * @Description: 下载文件
	 * @param
	 * @Create: 2012-8-7 上午09:07:25
	 * @author longweier
	 * @update logs
	 * @param response
	 * @param file
	 * @param fileName
	 * @throws Exception
	 * @return
	 * @throws UnsupportedEncodingException 
	 * @throws Exception
	 */
	public static void downloadFile(HttpServletResponse response,File file,String fileName) throws UnsupportedEncodingException{
		
		response.setContentType("APPLICATION/OCTET-STREAM;charset=UTF-8"); 
		
		response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName,"UTF-8"));
		
		InputStream is = null;
		OutputStream os = null;
		BufferedOutputStream bos = null;
		
		try {
			is = new  BufferedInputStream(new FileInputStream(file));
			
			
			os = response.getOutputStream();
			
			
			bos = new BufferedOutputStream(os);
			
			byte[] buffer = new byte[1024];
			
			int len = 0;
			
			while (-1 != (len = is.read(buffer)))
			{
				bos.write(buffer, 0, len);
				
			}
			bos.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				if(bos!=null){
					bos.close();
				}
				if(os !=null){
					os.close();
				}
				if(is!=null){
					is.close();
				}
				
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		
		
	}
	
}


